package com.example.sbeducation.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 静态资源配置
 */
@Configuration
public class ResourceConfig implements WebMvcConfigurer {

  @Value("${file.upload-dir}")
  private String uploadDir;

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 确保上传目录存在
    ensureUploadDirExists();

    // 配置静态资源映射
    // 将文件系统中的绝对路径作为资源位置
    File uploadPath = new File(uploadDir);
    String resourcePath = "file:" + uploadPath.getAbsolutePath() + "/";

    // 配置各类型资源的路径映射
    registry.addResourceHandler("/homework/**")
        .addResourceLocations(resourcePath + "homework/");

    registry.addResourceHandler("/submission/**")
        .addResourceLocations(resourcePath + "submission/");

    registry.addResourceHandler("/chat/**")
        .addResourceLocations(resourcePath + "chat/");

    registry.addResourceHandler("/avatar/**")
        .addResourceLocations(resourcePath + "avatar/");
  }

  /**
   * 确保上传目录存在
   */
  private void ensureUploadDirExists() {
    File uploadDirectory = new File(uploadDir);
    if (!uploadDirectory.exists()) {
      boolean created = uploadDirectory.mkdirs();
      if (!created) {
        throw new RuntimeException("无法创建上传文件目录: " + uploadDir);
      }
    }

    // 创建各类型的子目录
    createSubDir("homework");
    createSubDir("submission");
    createSubDir("chat");
    createSubDir("avatar");
  }

  /**
   * 创建子目录
   */
  private void createSubDir(String subDir) {
    File dir = new File(uploadDir + "/" + subDir);
    if (!dir.exists()) {
      boolean created = dir.mkdirs();
      if (!created) {
        throw new RuntimeException("无法创建子目录: " + subDir);
      }
    }
  }
}